package cn.fl.insroute.service.impl;

import java.util.ArrayList;
import java.util.List;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.BaseParamDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.utils.*;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.framework.base.constant.WebBaseConstant;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.insroute.api.IInsRouteModifyApiService;
import cn.fl.insroute.api.IInsRouteQueryApiService;
import cn.fl.insroute.condition.InsRouteBscInfoQC;
import cn.fl.insroute.dto.InsRouteInsResDTO;
import cn.fl.insroute.vo.InsRouteInsResVO;
import cn.fl.insroute.vo.InsRoutePrdInfoVO;
import cn.fl.insroute.vo.InsRoutePrpsFeeVO;
import cn.fl.insroute.voTransform.InsRouteBscInfoVOTransform;
import cn.fl.insroute.voTransform.InsRouteInsResVOTransform;
import cn.fl.preinsroute.condition.PreRouteInsResQC;
import cn.fl.preinsroute.constant.PreRouteConstant;
import cn.fl.preinsroute.service.IPreRouteInsResService;
import cn.fl.preinsroute.vo.PreRouteInsResVO;
import cn.fl.project.condition.PrjPrdBscInfoQueryCondition;
import cn.fl.project.condition.PrjQuatPrpsQueryCondition;
import cn.fl.project.condition.PrjSplBankAccRQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjQuatPrpsFeeConstant;
import cn.fl.project.service.*;
import cn.fl.project.transform.PrjBscInfoVOTransform;
import cn.fl.project.transform.PrjPrdBscInfoVOTransform;
import cn.fl.project.vo.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.dto.CstBankDTO;
import fl.spl.facade.spl.api.ISplInfoApiService;
import fl.spl.facade.spl.dto.SplBankDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fl.insroute.dto.InsRouteBscInfoDTO;
import cn.fl.insroute.service.IInsRouteBscInfoService;
import cn.fl.insroute.vo.InsRouteBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;

/**
 * @Description: 资管路由基础信息表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class InsRouteBscInfoServiceImpl implements IInsRouteBscInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IInsRouteBscInfoService.class);

	/**
	 * TODO 自定义 API 暴露服务
	 */
	//@Autowired
	//private I自定义ApiService 自定义ApiService;
	@Autowired
	private IInsRouteQueryApiService iInsRouteQueryApiService;

	@Autowired
	private IInsRouteModifyApiService iInsRouteModifyApiService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Autowired
	private IPrjPrdBscInfoService prjPrdBscInfoService;

	@Autowired
	private IPrjBscInfoService prjBscInfoService;

	@Autowired
	private IPreRouteInsResService preRouteInsResService;

	@Autowired
	private IPrjSplBankAccRService prjSplBankAccRService;

	@Autowired
	private ISplInfoApiService splInfoApiService;

	@Autowired
	private ICustomerApiService customerApiService;

	@Autowired
	private IVehicleStyleService vehicleStyleService;

    @Autowired
    private IPrjQuatPrpsService prjQuatPrpsService;

	@Override
	public InsRouteBscInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//TODO 业务逻辑
		InsRouteBscInfoDTO dto = null;//this.自定义ApiService.selectById(id);
		return InsRouteBscInfoVOTransform.toVO(dto);
	}

	@Override
	public Long add(InsRouteBscInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//return this.insRouteBscInfoApiService.add(InsRouteBscInfoVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.insRouteBscInfoApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}

	/**
	 * 删除
	 * @param ids
	 * @return
	 */
	public boolean removeByIds(List<Long> ids)throws BaseException{
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
	}

	@Override
	public boolean modify(InsRouteBscInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return this.iInsRouteModifyApiService.modifyInsRouteBscInfoDTO(InsRouteBscInfoVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		//return this.insRouteBscInfoApiService.searchListPage(page);
		//TODO 业务逻辑
		return null;
	}

	@Override
	public List<InsRouteBscInfoVO> searchList(InsRouteBscInfoQC insRouteBscInfoQC) throws BaseException {
		BaseLogUtils.info(logger,"searchList","条件查询资管路由基础信息.请求参数insRouteBscInfoQC：" + JSON.toJSONString(insRouteBscInfoQC),CurrentThreadContext.getCurrentUserName());
		List<InsRouteBscInfoDTO> insRouteBscInfoDTOS = this.iInsRouteQueryApiService.searchInsRouteBscInfoDTOList(insRouteBscInfoQC);
		BaseLogUtils.info(logger,"searchList","条件查询资管路由基础信息.返回结果insRouteBscInfoDTOS：" + JSON.toJSONString(insRouteBscInfoDTOS),CurrentThreadContext.getCurrentUserName());
		return InsRouteBscInfoVOTransform.toVOList(insRouteBscInfoDTOS);
	}

	@Override
	public InsRouteBscInfoVO searchListByPrjId(Long prjId) throws BaseException {
		BaseParamDTO baseParamDTO = new BaseParamDTO();
		baseParamDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
		baseParamDTO.setServiceCd(CurrentThreadContext.getFlServiceSysCd());
		baseParamDTO.setChannelCd(WebBaseConstant.CHANNEL_CD);
		baseParamDTO.setFrontCd(WebBaseConstant.CHANNEL_CD);
		InsRouteBscInfoDTO insRouteBscInfoDTO = this.iInsRouteQueryApiService.searchInsRouteBscInfoDTOListByPrjId(prjId,baseParamDTO);
		BaseLogUtils.info(logger,"searchListByPrjId","根据项目ID查询资管路由基础信息.返回结果insRouteBscInfoDTO：" + JSON.toJSONString(insRouteBscInfoDTO),CurrentThreadContext.getCurrentUserName());
		return InsRouteBscInfoVOTransform.toVO(insRouteBscInfoDTO);
	}

	@Override
	public Long modifyInsRouteBscInfo(PrjBscInfoVO prjBscInfoVO, InsRouteBscInfoVO insRouteBscInfoVO) throws BaseException {
		return this.iInsRouteModifyApiService.modifyInsRouteBscInfo(PrjBscInfoVOTransform.toDTO(prjBscInfoVO),InsRouteBscInfoVOTransform.toDTO(insRouteBscInfoVO));
	}

	@Override
	public DataResultDTO checkChange(Long checkedInsId, InsRouteBscInfoVO insRouteBscInfoVO) throws BaseException {
		DataResultDTO resultDTO = this.iInsRouteQueryApiService.checkChange(checkedInsId,InsRouteBscInfoVOTransform.toDTO(insRouteBscInfoVO));
		BaseLogUtils.info(logger,"checkChange","校验路由信息变化.返回结果resultDTO：" + JSON.toJSONString(resultDTO),CurrentThreadContext.getCurrentUserName());
		return resultDTO;
	}

	@Override
	public SysDictionaryDTO getFeeTypCdNm(String code) throws BaseException {
		if(StringUtils.isEmpty(code)){
			throw new BaseException("费用项类型为空");
		}
		SysDictionaryDTO sysDictionaryDTO = this.sysDictionaryApiService.getCode(CurrentThreadContext.getCurrentSysCd(), PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG, DictionaryConstant.CODE_PRJ_QUAT_FEE_TYP_CD,code);
		BaseLogUtils.info(logger,"getFeeTypCdNm","获取费用项名称.结果sysDictionaryDTO：" + JSON.toJSONString(sysDictionaryDTO),CurrentThreadContext.getCurrentUserName());
		return sysDictionaryDTO;
	}

	@Override
	public SysDictionaryDTO getCalBaseCdNm(String code) throws BaseException {
		if(StringUtils.isEmpty(code)){
			throw new BaseException("费用计算基数为空");
		}
		SysDictionaryDTO sysDictionaryDTO = this.sysDictionaryApiService.getCode(CurrentThreadContext.getCurrentSysCd(), PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG, DictionaryConstant.CODE_PRJ_QUAT_CAL_BASE_CD,code);
		BaseLogUtils.info(logger,"getCalBaseCdNm","获取费用计算基数名称.结果sysDictionaryDTO：" + JSON.toJSONString(sysDictionaryDTO),CurrentThreadContext.getCurrentUserName());
		return sysDictionaryDTO;
	}

	@Override
	public SysDictionaryDTO getCntWayCdNm(String code) throws BaseException {
		if(StringUtils.isEmpty(code)){
			throw new BaseException("费用计入方式为空");
		}
		SysDictionaryDTO sysDictionaryDTO = this.sysDictionaryApiService.getCode(CurrentThreadContext.getCurrentSysCd(), PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG, DictionaryConstant.CODE_PRJ_QUAT_CNT_WAY_CD,code);
		BaseLogUtils.info(logger,"getCntWayCdNm","获取费用计入方式名称.结果sysDictionaryDTO：" + JSON.toJSONString(sysDictionaryDTO),CurrentThreadContext.getCurrentUserName());
		return sysDictionaryDTO;
	}

	@Override
	public DataResultDTO routeRes(InsRouteBscInfoVO insRouteBscInfoVO)throws BaseException {
		BaseLogUtils.info(logger,"routeRes","筛选结果（路由）.请求参数insRouteBscInfoVO：" + JSON.toJSONString(insRouteBscInfoVO),CurrentThreadContext.getCurrentUserName());
		DataResultDTO routeRes = this.iInsRouteQueryApiService.routeRes(InsRouteBscInfoVOTransform.toDTO(insRouteBscInfoVO));
		BaseLogUtils.info(logger,"routeRes","筛选结果（路由）.结果routeRes：" + JSON.toJSONString(routeRes),CurrentThreadContext.getCurrentUserName());
		return routeRes;
	}

	@Override
	public DataResultDTO routeResPrps(PrjQuatPrpsVO prjQuatPrps,Integer flag) throws BaseException {
		BaseLogUtils.info(logger,"routeResPrps","筛选结果(方案).请求参数prjQuatPrps：" + JSON.toJSONString(prjQuatPrps),CurrentThreadContext.getCurrentUserName());
		if(prjQuatPrps == null){
			throw new BaseException("方案信息为空");
		}
		DataResultDTO resultDTO = new DataResultDTO(BaseConstant.IS_YESNO_YES,"筛选结果通过");
		Long prjId = prjQuatPrps.getPrjId();
		PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
		BaseLogUtils.info(logger,"routeResPrps","筛选结果(方案).项目信息prjBscInfoVO：" + JSON.toJSONString(prjBscInfoVO),CurrentThreadContext.getCurrentUserName());
		if(prjBscInfoVO == null){
			throw new BaseException("未找到项目信息");
		}
		Long fundRasInsId = prjBscInfoVO.getFundRasInsId();
		List<SysDictionaryDTO> sysDictionaryDTOS = this.searchRouteCheck();
		BaseLogUtils.info(logger,"routeResPrps","筛选结果(方案).资管路由验证sysDictionaryDTOS：" + JSON.toJSONString(sysDictionaryDTOS) + "-prjId:" + prjId,CurrentThreadContext.getCurrentUserName());
		if(CollectionUtils.isNotEmpty(sysDictionaryDTOS)){
			for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOS){
				String code = sysDictionaryDTO.getCode();
				String codeAttr2 = sysDictionaryDTO.getCodeAttr2();
				if(StringUtils.isNotBlank(code)){
					String[] split = code.split("-");
					if(split.length == 2
							&&split[0].equals(prjBscInfoVO.getPrjTypCd())
							&& split[1].equals(prjBscInfoVO.getBuOrgCd())){
						/**
						 * 是否强校验（是：合规为止 否：如果之前没有选机构不走路由，如果选了机构走路有）
						 */
						if(StringUtils.isNotEmpty(codeAttr2)
								&& codeAttr2.equals(BaseConstant.IS_YESNO_YES_STR)){
							resultDTO = this.route(prjQuatPrps,flag);
						}else if(fundRasInsId != null){
							resultDTO = this.route(prjQuatPrps,flag);
						}
						JSONObject resObj = (JSONObject)resultDTO.getData();
						if(resObj!=null){
							resObj.put("isCheckRouteFlag",codeAttr2);
						}
						resultDTO.setData(resObj);
						break;
					}
				}
			}
		}
		BaseLogUtils.info(logger,"routeResPrps","筛选结果（方案）.返回结果处理后resultDTO：" + JSON.toJSONString(resultDTO),CurrentThreadContext.getCurrentUserName());
		return resultDTO;
	}

	@Override
	public Boolean synchroInfo(Long prjId, Long mediationFeeAmt, Long usrId) throws BaseException {
		return this.iInsRouteModifyApiService.synchroInfo(prjId,mediationFeeAmt,usrId);
	}

	@Override
	public Boolean synchroInsInfo(List<PrjPrdBscInfoVO> prjPrdBscInfoVOList, Integer flag) throws BaseException {
		return this.iInsRouteModifyApiService.synchroInsInfo(PrjPrdBscInfoVOTransform.toDTOList(prjPrdBscInfoVOList),CurrentThreadContext.getCurrentUserId(),flag);
	}

    @Override
    public Boolean synchroInsInfoEsc(List<PrjPrdBscInfoVO> prjPrdBscInfoVOList, Integer flag) throws BaseException {
        return this.iInsRouteModifyApiService.synchroInsInfoEsc(PrjPrdBscInfoVOTransform.toDTOList(prjPrdBscInfoVOList),CurrentThreadContext.getCurrentUserId(),flag);
    }

	/**
	 * 筛选
	 * @param prjQuatPrps
	 * @param flag 0 测算 1 方案
	 * @return
	 * @throws BaseException
	 */
	private DataResultDTO route(PrjQuatPrpsVO prjQuatPrps,Integer flag) throws BaseException {
		DataResultDTO res = new DataResultDTO(BaseConstant.IS_YESNO_YES,"筛选结果通过");
		Long prjId = prjQuatPrps.getPrjId();
		PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
		BaseLogUtils.info(logger,"route","筛选结果(方案).项目信息prjBscInfoVO：" + JSON.toJSONString(prjBscInfoVO),CurrentThreadContext.getCurrentUserName());
		if(prjBscInfoVO == null){
			throw new BaseException("未找到项目信息");
		}
		Long fundRasInsId = prjBscInfoVO.getFundRasInsId();
        String prjTypCd = prjBscInfoVO.getPrjTypCd();
        /**
		 * 1.路由主信息
		 */
		InsRouteBscInfoVO insRouteBscInfo = this.searchListByPrjId(prjId);
		BaseLogUtils.info(logger,"route","筛选结果(方案).路由信息insRouteBscInfo：" + JSON.toJSONString(insRouteBscInfo),CurrentThreadContext.getCurrentUserName());
		if(insRouteBscInfo == null){
			throw new BaseException("路由信息为空");
		}
		String isPreInt = insRouteBscInfo.getIsPreInt();
        String isVisit = insRouteBscInfo.getIsVisit();
        if(PrjBscInfoConstant.PRJ_TYP_CD_CDDYWUL.equals(prjTypCd)
                || PrjBscInfoConstant.PRJ_TYP_CD_ESCJYD.equals(prjTypCd)
                || PrjBscInfoConstant.PRJ_TYP_CD_OWNJYD.equals(prjTypCd)){
            if(StringUtils.isBlank(isVisit)){
                throw new BaseException("是否家访费为空");
            }
        }
        InsRouteBscInfoVO insRouteBscInfoVO = new InsRouteBscInfoVO();
		insRouteBscInfoVO.setPrjId(prjId);
		insRouteBscInfoVO.setChannel(BaseConstant.IS_YESNO_YES_STR);//方案
		if(BaseConstant.IS_YESNO_YES == flag){
			insRouteBscInfoVO.setContAmt(prjQuatPrps.getContAmt());
		}else if(BaseConstant.IS_YESNO_NO == flag){
			insRouteBscInfoVO.setContAmt(prjQuatPrps.getContAmt() == null? 0 : DecimalUtils.convertYuanToFen(prjQuatPrps.getContAmt()).doubleValue());
		}else{
			throw new BaseException("路由来源异常");
		}
		insRouteBscInfoVO.setLsPd(prjQuatPrps.getLsPd());
		if(prjQuatPrps.getIsBp() != null){
			insRouteBscInfoVO.setIsBp(prjQuatPrps.getIsBp());
		}else{
			insRouteBscInfoVO.setIsBp(insRouteBscInfo.getIsBp());
		}
		insRouteBscInfoVO.setAnnIntRatePct(prjQuatPrps.getAnnIntRatePct());
		insRouteBscInfoVO.setIsFarmer(insRouteBscInfo.getIsFarmer());
		insRouteBscInfoVO.setIsCheckOut(insRouteBscInfo.getIsCheckOut());
		insRouteBscInfoVO.setCheckOutDt(insRouteBscInfo.getCheckOutDt());
		insRouteBscInfoVO.setIsLic(insRouteBscInfo.getIsLic());
		insRouteBscInfoVO.setLicDt(insRouteBscInfo.getLicDt());
		insRouteBscInfoVO.setIsLicAgain(insRouteBscInfo.getIsLicAgain());
		insRouteBscInfoVO.setLicAgainDt(insRouteBscInfo.getLicAgainDt());
		insRouteBscInfoVO.setRgnCyCd(insRouteBscInfo.getRgnCyCd());
		insRouteBscInfoVO.setRgnPrCd(insRouteBscInfo.getRgnPrCd());
		insRouteBscInfoVO.setIsPreInt(isPreInt);
		insRouteBscInfoVO.setIsVisit(isVisit);
		insRouteBscInfoVO.setPayWayCd(insRouteBscInfo.getPayWayCd());
		/**
		 * 2.设备信息
		 */
		List<InsRoutePrdInfoVO> insRoutePrdInfoVOList = new ArrayList<InsRoutePrdInfoVO>();
		PrjPrdBscInfoQueryCondition prjPrdBscInfoQueryCondition = new PrjPrdBscInfoQueryCondition();
		prjPrdBscInfoQueryCondition.setPrjId(prjId);
		List<PrjPrdBscInfoVO> prjPrdBscInfoVOS = this.prjPrdBscInfoService.searchList(prjPrdBscInfoQueryCondition);
		BaseLogUtils.info(logger,"route","筛选结果(方案).项目产品信息prjPrdBscInfoVOS：" + JSON.toJSONString(prjPrdBscInfoVOS),CurrentThreadContext.getCurrentUserName());
		Long mediationFeeAmtSum = 0l;
		int sum = 0;
		Long oriMediationFeeAmt = 0l;
		if(CollectionUtils.isNotEmpty(prjPrdBscInfoVOS)){
			Long mediationFeeAmt = insRouteBscInfo.getInsRoutePrdInfoVOList().get(0).getMediationFeeAmt();
			if(mediationFeeAmt == null){
				mediationFeeAmt = 0l;
			}
			for(PrjPrdBscInfoVO prjPrdBscInfoVO : prjPrdBscInfoVOS){
				sum += prjPrdBscInfoVO.getPrdQty();
				InsRoutePrdInfoVO insRoutePrdInfoVO = new InsRoutePrdInfoVO();
				insRoutePrdInfoVO.setPrjId(prjId);
				insRoutePrdInfoVO.setPrdNm(prjPrdBscInfoVO.getPrdNm());
				insRoutePrdInfoVO.setGuidePc(DecimalUtils.convertYuanToFen(prjPrdBscInfoVO.getGuidePc()).doubleValue());
				insRoutePrdInfoVO.setMediationFeeAmt(mediationFeeAmt);
				insRoutePrdInfoVO.setPrdQty(prjPrdBscInfoVO.getPrdQty());
				insRoutePrdInfoVO.setPrdTypCd(prjPrdBscInfoVO.getPrdTypCd());
				insRoutePrdInfoVO.setPrdId(Long.valueOf(prjPrdBscInfoVO.getPrdCd()));
				insRoutePrdInfoVO.setBrCd(prjPrdBscInfoVO.getBrCd());
				if(PrjBscInfoConstant.PRJ_TYP_CD_CDDYWUL.equals(prjTypCd)
						|| PrjBscInfoConstant.PRJ_TYP_CD_ESCJYD.equals(prjTypCd)
						|| PrjBscInfoConstant.PRJ_TYP_CD_OWNJYD.equals(prjTypCd)){
					insRoutePrdInfoVO.setReleaseDt(prjPrdBscInfoVO.getReleaseDate());
					insRoutePrdInfoVO.setVehAmt(DecimalUtils.convertYuanToFen(prjPrdBscInfoVO.getVehVal()));
					insRoutePrdInfoVO.setVehId(prjPrdBscInfoVO.getCarSourceId());
					insRoutePrdInfoVO.setVehMdl(prjPrdBscInfoVO.getPrdMdl());
					insRoutePrdInfoVO.setVehNo(prjPrdBscInfoVO.getCarNo());
					insRoutePrdInfoVO.setRegDt(prjPrdBscInfoVO.getCertDt());
					insRoutePrdInfoVO.setReleaseDt(prjPrdBscInfoVO.getReleaseDate());
					if(StringUtils.isNotBlank(prjPrdBscInfoVO.getPrdCd())){
						SysDictionaryDTO purposeDictionaryDTO = this.vehicleStyleService.getPurposeDictionaryDTO(prjPrdBscInfoVO.getPrdCd());
						if(purposeDictionaryDTO != null){
							insRoutePrdInfoVO.setPrdNmMdl(purposeDictionaryDTO.getCodeNm());
						}
					}
					/**
					 * 账号类型
					 */
					PrjSplBankAccRQueryCondition condition = new PrjSplBankAccRQueryCondition();
					condition.setPrjPrdId(prjPrdBscInfoVO.getId());
					condition.setIsDel(BaseConstant.IS_YESNO_NO);
					List<PrjSplBankAccRVO> prjSplBankAccRVOS = this.prjSplBankAccRService.searchList(condition);
					String bankNoTypCd = "";
                    List<SysDictionaryDTO> accTypCds = this.sysDictionaryApiService.searchGroup(WebBaseConstant.SYS_SYS_CD, WebBaseConstant.SYS_P_ORG_CD, DictionaryConstant.CODE_GRP_CST_NP_ACC_TYP_CD);
					if(CollectionUtils.isNotEmpty(prjSplBankAccRVOS)){
						for (PrjSplBankAccRVO prjSplBankAccRVO : prjSplBankAccRVOS) {
							String receiveTypeCd = prjSplBankAccRVO.getReceiveTypeCd();
							Long splAccNoId = prjSplBankAccRVO.getSplAccNoId();
							if(CapitalConstant.CODE_SPL_BK_PURP_CD_1.equals(prjSplBankAccRVO.getPurpCd())){
								if(CapitalConstant.CODE_PAYEE_TYP_CD_1.equals(receiveTypeCd)){
									SplBankDTO splBankDTO = this.splInfoApiService.selectPrdSplBankById(splAccNoId);
									BaseLogUtils.info(logger, "synchroInsInfoEsc", "同步路由信息.二手车.splBankDTO", JSONObject.toJSONString(splBankDTO));
									bankNoTypCd = splBankDTO.getBizTypCd();
								}else if(CapitalConstant.CODE_PAYEE_TYP_CD_2.equals(receiveTypeCd) || CapitalConstant.CODE_PAYEE_TYP_CD_8.equals(receiveTypeCd)){
									CstBankDTO cstBankDTO = this.customerApiService.selectCstBankById(splAccNoId);
									BaseLogUtils.info(logger, "synchroInsInfoEsc", "同步路由信息.二手车.cstBankDTO", JSONObject.toJSONString(cstBankDTO));
									bankNoTypCd = cstBankDTO.getAccTypCd();
                                    if(CollectionUtils.isNotEmpty(accTypCds) && StringUtils.isNotBlank(bankNoTypCd)){
                                        for (SysDictionaryDTO accTypCd : accTypCds) {
                                            String code = accTypCd.getCode();
                                            if(StringUtils.isNotBlank(code) && code.equals(bankNoTypCd)){
                                                bankNoTypCd = accTypCd.getCodeAttr2();
                                            }
                                        }
                                    }
								}else{
									throw new BaseException("收款账号查询异常");
								}
							}
						}
					}
					insRoutePrdInfoVO.setBankNoTypCd(bankNoTypCd);
				}
				insRoutePrdInfoVOList.add(insRoutePrdInfoVO);
				mediationFeeAmtSum += insRoutePrdInfoVO.getMediationFeeAmt()*insRoutePrdInfoVO.getPrdQty();
			}
            oriMediationFeeAmt = mediationFeeAmt*sum;
		}
		insRouteBscInfoVO.setInsRoutePrdInfoVOList(insRoutePrdInfoVOList);
		/**
		 * 3.费用项数据
		 */
		List<InsRoutePrpsFeeVO> insRoutePrpsFeeVOList = new ArrayList<InsRoutePrpsFeeVO>();
		List<PrjQuatPrpsFeeVO> prjQuatPrpsFeelist = prjQuatPrps.getPrjQuatPrpsFeelist();
		if(CollectionUtils.isEmpty(prjQuatPrpsFeelist)){
			throw new BaseException("费用项集合为空");
		}
		List<String> feeTypCdList = new ArrayList<String>();
		boolean fee05 = false;
		Double fee78 = 0d;
		Double fee76 = 0d;
		Double firstAmt = 0d;
		for (PrjQuatPrpsFeeVO prjQuatPrpsFeeVO : prjQuatPrpsFeelist){
			String feeTypCd = prjQuatPrpsFeeVO.getFeeTypCd();
			Double feeAmt = prjQuatPrpsFeeVO.getFeeAmt();
			if(PrjQuatPrpsFeeConstant.FEE_TYP_CD_01.equals(feeTypCd)
					|| PrjQuatPrpsFeeConstant.FEE_TYP_CD_02.equals(feeTypCd)
					|| PrjQuatPrpsFeeConstant.FEE_TYP_CD_52.equals(feeTypCd)
					|| PrjQuatPrpsFeeConstant.FEE_TYP_CD_63.equals(feeTypCd)
					|| PrjQuatPrpsFeeConstant.FEE_TYP_CD_64.equals(feeTypCd)
                    || PrjQuatPrpsFeeConstant.FEE_TYP_CD_30.equals(feeTypCd)
                    || PrjQuatPrpsFeeConstant.FEE_TYP_CD_67.equals(feeTypCd)
                    || PrjQuatPrpsFeeConstant.PRJ_FEE_TYP_INS_COLLATERAL.equals(feeTypCd)){
				InsRoutePrpsFeeVO insRoutePrpsFeeVO = new InsRoutePrpsFeeVO();
				insRoutePrpsFeeVO.setPrjId(prjId);
				insRoutePrpsFeeVO.setCntWayCd(prjQuatPrpsFeeVO.getCntWayCd());
				insRoutePrpsFeeVO.setCalBaseCd(prjQuatPrpsFeeVO.getCalBaseCd());
				insRoutePrpsFeeVO.setFeeTypCd(prjQuatPrpsFeeVO.getFeeTypCd());
				insRoutePrpsFeeVO.setIsFixedAmt(prjQuatPrpsFeeVO.getIsFixedAmt());
				if(BaseConstant.IS_YESNO_YES == flag){
					insRoutePrpsFeeVO.setFeeAmt(feeAmt);
				}else if(BaseConstant.IS_YESNO_NO == flag){
					insRoutePrpsFeeVO.setFeeAmt(feeAmt == null? 0: DecimalUtils.convertYuanToFen(feeAmt).doubleValue());
				}else{
					throw new BaseException("路由来源异常");
				}
				if(PrjQuatPrpsFeeConstant.FEE_TYP_CD_01.equals(feeTypCd)){
					firstAmt = insRoutePrpsFeeVO.getFeeAmt();
				}
				insRoutePrpsFeeVO.setFeePct(prjQuatPrpsFeeVO.getFeePct());
				insRoutePrpsFeeVO.setIsAllowChg(prjQuatPrpsFeeVO.getIsAllowChg());
				insRoutePrpsFeeVOList.add(insRoutePrpsFeeVO);
				feeTypCdList.add(feeTypCd);
			}
            if(PrjQuatPrpsFeeConstant.FEE_TYP_CD_78.equals(feeTypCd)){
                fee78= feeAmt;
            }
            if(PrjQuatPrpsFeeConstant.FEE_TYP_CD_76.equals(feeTypCd)){
                fee76= (feeAmt == null ? 0d : feeAmt);
            }
			if(PrjQuatPrpsFeeConstant.PRJ_FEE_TYP_CONSULT_2.equals(feeTypCd) && feeAmt != null && feeAmt > 0){
				fee05 = true;
			}
		}
		if(PrjBscInfoConstant.PRJ_TYP_CD_CDDYWUL.equals(prjTypCd)
                || PrjBscInfoConstant.PRJ_TYP_CD_ESCJYD.equals(prjTypCd)
                || PrjBscInfoConstant.PRJ_TYP_CD_OWNJYD.equals(prjTypCd)){
		    if(BaseConstant.IS_YESNO_NO_STR.equals(isVisit) && fee78 != 0d){
                throw new BaseException("家访费不可大于0");
            }
            if(BaseConstant.IS_YESNO_YES_STR.equals(isVisit) && !(fee78 > 0d)){
                throw new BaseException("家访费需大于0");
            }
        }

		if(BaseConstant.IS_YESNO_YES_STR.equals(isPreInt) && !fee05){
			throw new BaseException("咨询费2需大于0");
		}
		if(firstAmt<fee76){
			throw new BaseException("首付金额不可低于调节费，请核实");
		}
		BaseLogUtils.info(logger,"route","筛选结果(方案).费用项feeTypCdList：" + JSON.toJSONString(feeTypCdList),CurrentThreadContext.getCurrentUserName());
		List<InsRoutePrpsFeeVO> insRoutePrpsFeeList = insRouteBscInfo.getInsRoutePrpsFeeVOList();
		if(CollectionUtils.isEmpty(insRoutePrpsFeeList)){
			throw new BaseException("费用项为空");
		}
		for (InsRoutePrpsFeeVO insRoutePrpsFeeVO : insRoutePrpsFeeList){
			String feeTypCd = insRoutePrpsFeeVO.getFeeTypCd();
			if(StringUtils.isNotEmpty(feeTypCd) && !(feeTypCdList.contains(feeTypCd))){
				insRoutePrpsFeeVOList.add(insRoutePrpsFeeVO);
			}
		}
		insRouteBscInfoVO.setInsRoutePrpsFeeVOList(insRoutePrpsFeeVOList);
		BaseLogUtils.info(logger,"route","筛选结果(方案).路由封装结果insRouteBscInfoVO：" + JSON.toJSONString(insRouteBscInfoVO),CurrentThreadContext.getCurrentUserName());
		DataResultDTO routeRes = this.routeRes(insRouteBscInfoVO);
		BaseLogUtils.info(logger,"route","筛选结果（方案）.返回结果routeRes：" + JSON.toJSONString(routeRes),CurrentThreadContext.getCurrentUserName());
		/**
		 * 解析结果（判断本次筛选出的机构包含已选中的机构）
		 */
		JSONObject obj = new JSONObject();
		Long preRouteId = prjBscInfoVO.getPreRouteId();
		Long preResId = prjBscInfoVO.getPreResId();
		Long preInsId = 0l;
		Integer resTypCd = PreRouteConstant.PRE_ROUTE_INS_RES_STS_1;
		PreRouteInsResVO preRouteInsResVO = null;
		List<Long> preInsIdList = new ArrayList<Long>();
		if( preResId != null && preRouteId != null){
			preRouteInsResVO = this.preRouteInsResService.selectById(preResId);
			PreRouteInsResQC preRouteInsResQC = new PreRouteInsResQC();
			preRouteInsResQC.setResTypCd(PreRouteConstant.PRE_ROUTE_INS_RES_STS_1);
			preRouteInsResQC.setRouteId(preRouteId);
			List<PreRouteInsResVO> preRouteInsResVOS = this.preRouteInsResService.searchList(preRouteInsResQC);
			if(preRouteInsResVO != null){
				resTypCd = preRouteInsResVO.getResTypCd();
				preInsId = preRouteInsResVO.getInsId();
			}
			if(CollectionUtils.isNotEmpty(preRouteInsResVOS)){
				for (PreRouteInsResVO routeInsResVO : preRouteInsResVOS) {
					if((routeInsResVO.getInsId()).equals(preInsId)){
						continue;
					}
					preInsIdList.add(routeInsResVO.getInsId());
				}
			}
		}
		if(routeRes!=null && routeRes.getSuccess() == BaseConstant.IS_YESNO_YES){
			if(routeRes.getData() == null){
				throw new BaseException("机构筛选异常");
			}
			JSONObject resObj = (JSONObject)routeRes.getData();
			Object isAllowNonIns = resObj.get("isAllowNonIns");
			if(resObj.get("gctInsResList") != null){
				List<InsRouteInsResDTO> insRouteInsResVOS = (List<InsRouteInsResDTO>)(resObj.get("gctInsResList"));
                if(CollectionUtils.isNotEmpty(insRouteInsResVOS)){
                    for (InsRouteInsResDTO insRouteInsResDTO : insRouteInsResVOS) {
                        if(prjBscInfoVO.getFundRasInsId() != null && (prjBscInfoVO.getFundRasInsId()).equals(insRouteInsResDTO.getInsId())){
                            insRouteInsResDTO.setIsChecked(BaseConstant.IS_YESNO_YES);
                        }else{
                            insRouteInsResDTO.setIsChecked(BaseConstant.IS_YESNO_NO);
                        }
                    }
                }
				BaseLogUtils.info(logger,"route","筛选结果（方案）.gctInsResList=" + JSON.toJSONString(insRouteInsResVOS),CurrentThreadContext.getCurrentUserName());
				if(CollectionUtils.isNotEmpty(insRouteInsResVOS)){
					if(!(fundRasInsId == null
							&& isAllowNonIns != null
							&& isAllowNonIns.equals(BaseConstant.IS_YESNO_YES))){
						List<Long> insIdList = new ArrayList<Long>();
                        long mediationFeeAmt = 0;
                        for(InsRouteInsResDTO insRouteInsResDTO : insRouteInsResVOS){
						    if(StringUtils.isNotEmpty(fundRasInsId) && fundRasInsId.equals(insRouteInsResDTO.getInsId())){
                                mediationFeeAmt = insRouteInsResDTO.getMediationFeeAmt() == null ? 0 : insRouteInsResDTO.getMediationFeeAmt();
                            }
							insIdList.add(insRouteInsResDTO.getInsId());
						}
						if(fundRasInsId != null && insIdList.contains(fundRasInsId)){
                            if(PrjBscInfoConstant.PRJ_TYP_CD_CTYW.equals(prjTypCd)
                                    || PrjBscInfoConstant.PRJ_TYP_CD_CPYW.equals(prjTypCd)){
                                obj.put("fee76", mediationFeeAmt);
                                obj.put("oriMediationFeeAmt", oriMediationFeeAmt);
                                double sumFee76 = DecimalUtils.div(fee76-mediationFeeAmt,100);
                                sumFee76 = DecimalUtils.round(DecimalUtils.div(sumFee76,sum,0),0,0)*sum;
                                obj.put("sumFee76", DecimalUtils.convertYuanToFen(sumFee76));
                                res.setData(obj);
                            }
							BaseLogUtils.info(logger,"route","筛选结果（方案）.无需处理prjId=" + prjId,CurrentThreadContext.getCurrentUserName());
							return res;
						}
						BaseLogUtils.info(logger,"route","筛选结果（方案）.before=" + JSON.toJSONString(insRouteInsResVOS),CurrentThreadContext.getCurrentUserName());
						res.setSuccess(BaseConstant.IS_YESNO_NO);
						List<InsRouteInsResDTO> insRouteInsResDTOS = new ArrayList<InsRouteInsResDTO>();
						InsRouteInsResDTO insRouteInsResDTOOwn = null;
						if(PreRouteConstant.PRE_ROUTE_INS_RES_STS_1.equals(resTypCd)){
							if(preInsId != 0l){
								for (InsRouteInsResDTO insRouteInsResDTO : insRouteInsResVOS) {
									if(preInsIdList.contains(insRouteInsResDTO.getInsId())){
										insRouteInsResDTO.setIsShowBiz(BaseConstant.IS_YESNO_NO);
										continue;
									}
									insRouteInsResDTOS.add(insRouteInsResDTO);
								}
								if(CollectionUtils.isNotEmpty(insRouteInsResDTOS)){
									for (InsRouteInsResDTO insRouteInsResDTO : insRouteInsResDTOS) {
										if(preInsId.equals(insRouteInsResDTO.getInsId())){
											insRouteInsResDTOOwn = insRouteInsResDTO;
										}
									}
								}
								if(insRouteInsResDTOOwn != null){
									for (InsRouteInsResDTO insRouteInsResDTO : insRouteInsResVOS) {
										if(!(preInsId.equals(insRouteInsResDTO.getInsId()))){
											insRouteInsResDTO.setIsShowBiz(BaseConstant.IS_YESNO_NO);
										}
									}
								}
							}
						}else{
							res.setSuccess(BaseConstant.IS_YESNO_YES);
							return res;
						}
						obj.put("isAllowNonIns", isAllowNonIns);
						obj.put("gctInsResList",(InsRouteInsResVOTransform.toVOList(insRouteInsResVOS)));
						obj.put("ungctInsResList",(List<InsRouteInsResVO>)(resObj.get("ungctInsResList")));
						BaseLogUtils.info(logger,"route","筛选结果（方案）.after=" + JSON.toJSONString(insRouteInsResVOS),CurrentThreadContext.getCurrentUserName());
					}
				}else if(fundRasInsId != null){
					res.setSuccess(BaseConstant.IS_YESNO_NO);
					obj.put("isAllowNonIns", isAllowNonIns);
					obj.put("ungctInsResList",(List<InsRouteInsResVO>)(resObj.get("ungctInsResList")));
				}
			}else{
				if(fundRasInsId != null){
					res.setSuccess(BaseConstant.IS_YESNO_NO);
					obj.put("isAllowNonIns", isAllowNonIns);
					obj.put("ungctInsResList",(List<InsRouteInsResVO>)(resObj.get("ungctInsResList")));
				}
			}
		}else{
			throw new BaseException("机构筛选异常");
		}
		res.setData(obj);
		BaseLogUtils.info(logger,"route","筛选结果（方案）.解析后返回结果res：" + JSON.toJSONString(res),CurrentThreadContext.getCurrentUserName());
		return res;
	}

    @Override
    public List<SysDictionaryDTO> searchRouteCheck() throws BaseException{
        return this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd(), "PRJ0203");
    }

	@Override
	public boolean changePreInsResInfo(Long prjId, Long OldPreResId, Long preResId) throws BaseException {
		return this.iInsRouteModifyApiService.changePreInsResInfo(prjId,OldPreResId,preResId);
	}

}
